package com.wltt.product.frfront;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.ExitCodeGenerator;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;

@SpringBootApplication
@MapperScan("com.wltt.product.frfront.mapper")
@EnableTransactionManagement
@EnableScheduling
public class FrFrontApplication {
    private static RandomAccessFile randomAccessFile;
    private static FileChannel channel;
    private static FileLock lock;

    public static void main(String[] args) {
        try {
            File lockFile = new File("./fr-front.lock");
            if (!lockFile.exists()) {
                lockFile.createNewFile();
            }

            randomAccessFile = new RandomAccessFile("fr-front.lock", "rw");
            channel = randomAccessFile.getChannel();
            lock = channel.tryLock();
            if (lock == null) {
                System.out.println("应用已经在运行。");
                return;
            }
            SpringApplication.run(FrFrontApplication.class, args);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Component
    public class MyExitListener implements ApplicationListener<ContextClosedEvent>, ExitCodeGenerator {
        @Override
        public void onApplicationEvent(ContextClosedEvent event) {
            if (lock != null) {
                try {
                    lock.release();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (channel != null) {
                try {
                    channel.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (randomAccessFile != null) {
                try {
                    randomAccessFile.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        @Override
        public int getExitCode() { return 0; } // 返回退出码，非必须实现，除非你需要自定义退出码。
    }
}
